package net.pws.oos.web.mobile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.pws.common.jackson.JsonUtils;
import net.pws.common.security.SecurityContext;
import net.pws.common.util.StringUtils;
import net.pws.oos.biz.model.Organization;
import net.pws.oos.biz.model.User;
import net.pws.oos.biz.query.SystemManageFinder;
import net.pws.oos.biz.query.parameter.OrganizationQueryParameter;
import net.pws.oos.biz.query.parameter.UserQueryParameter;
import net.pws.oos.biz.service.SystemManageService;
import net.pws.oos.security.SecurityUtils;
import net.pws.oos.web.SystemManageAction;
import net.pws.oos.web.dto.SimpleTreeNode;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/biz/mobile/system")
@SuppressWarnings("rawtypes")
public class MobileSystemAction {
    
    private final transient Log logger = LogFactory.getLog(MobileSystemAction.class);
    
    @Autowired
    private SystemManageFinder systemManageFinder;
    
    @Autowired
    private SystemManageService systemManageService;
    
    @Autowired
    private SystemManageAction systemManageAction;
    
    @RequestMapping("/user/changePassword.json")
    @ResponseBody
    public Object changePassword(String id,
                                 String oldPassword,
                                 String newPassword,
                                 String newPasswordRetry) {
        try {
            if (!newPassword.equals(newPasswordRetry)) {
                return JsonUtils.failedMap("两次新密码输入不一致！");
            }
            if (id == null) {
                id = SecurityContext.getContext().getId();
            }
            systemManageService.changeUserPassword(id, oldPassword, newPassword);
            return JsonUtils.succeedMap(null);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/user/tree.json")
    @ResponseBody
    public Object getUserTree(String id) {
        try {
            List<SimpleTreeNode> nodes = new ArrayList<SimpleTreeNode>();
            List<Organization> organs = systemManageFinder.getOrganizationChildren(id);
            for (Organization organization : organs) {
                nodes.add(SimpleTreeNode.from(organization));
            }
            if (StringUtils.isNotBlank(id)) {
                List<User> users = systemManageFinder.getUserListByOrgan(id);
                for (User user : users) {
                    nodes.add(SimpleTreeNode.from(user));
                }
            }
            return JsonUtils.succeedMap(nodes);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/user/count.json")
    @ResponseBody
    public Object getUserCount(UserQueryParameter queryParams) {
        queryParams = initUserParameterByRole(queryParams);
        try {
            return JsonUtils.succeedMap(systemManageFinder.countOurUser(queryParams));
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/user/list.json")
    @ResponseBody
    public Object getUserList(UserQueryParameter queryParams) {
        queryParams = initUserParameterByRole(queryParams);
        try {
            List<Map> users = systemManageFinder.getOurUserMapList(queryParams,
                                                                   queryParams.getStart(),
                                                                   queryParams.getLimit());
            return JsonUtils.succeedMap(users);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/organ/count.json")
    @ResponseBody
    public Object getOrganizationCount(OrganizationQueryParameter queryParams) {
        return systemManageAction.getOrganizationCount(queryParams);
    }
    
    @RequestMapping("/organ/list.json")
    @ResponseBody
    public Object getOrganizationList(OrganizationQueryParameter queryParams) {
        return systemManageAction.getOrganizationList(queryParams);
    }
    
    private UserQueryParameter initUserParameterByRole(UserQueryParameter queryParameter) {
        if (queryParameter == null) {
            queryParameter = new UserQueryParameter();
        }
        
        if (StringUtils.isBlank(queryParameter.getOrganId())) {
            queryParameter.setOrganId(SecurityUtils.currentUser().getOrganId());
        }
        return queryParameter;
    }
    
}
